package cn.wolfcode.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.query.JsonResult;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.utils.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@Controller
public class LoginController {
    @Autowired
    private IPermissionService permissionService;

    @Autowired
    private IEmployeeService employeeService;

    @RequestMapping("/login")
    @ResponseBody
    public JsonResult login(String username, String password, HttpSession session){
            Employee employee=employeeService.login(username,password);
            //session.setAttribute("EMPLOYEE_IN_SESSION", employee);
            UserContext.setCurrentUser(employee);
            //如果该用户不为管理员的话，就将权限存入ssension中
            if(!employee.isAdmin()){
                List<String> list = permissionService.selectAllPermissions(employee.getId());
                //session.setAttribute("EXPRESSION_IN_SESSION", list);
                UserContext.setExpressions(list);
            }
            return new JsonResult();
    }

    //@RequestMapping("/loginOut")
    //public void loginOut(HttpSession session, HttpServletResponse response) throws IOException {
    //    session.invalidate();//删除会话
    //    response.sendRedirect("/login.html");
    //}

    @RequestMapping("/loginOut")
    public String loginOut(HttpSession session){
        session.invalidate();//删除会话
        return "redirect:login.html";
    }
}
